package com.vaye.im.config;

import com.google.common.collect.Lists;
import com.vaye.common.constant.CacheConstant;
import com.vaye.common.utils.RedisUtil;
import com.vaye.common.utils.SpringContextUtils;
import com.vaye.im.listener.RedisTopicListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.List;

/**
 * 分类名称
 *
 * @author wangzhiyong
 * @module admin
 * @date 2023年01月19日 上午11:11
 */
@Configuration
@Slf4j
public class BeansConfig {

    @Bean
    public RedisUtil redisUtil(){
        log.info("init RedisUtil");
        return new RedisUtil();
    }

    @Bean
    public SpringContextUtils springContextUtils(){
        log.info("init springContextUtils");
        return new SpringContextUtils();
    }

    /**
     * 添加spring提供的RedisMessageListenerContainer到容器
     * @param connectionFactory
     * @return
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }

    /**
     * 添加自己的监听器到容器中（监听指定topic）
     * @param container
     * @param stringRedisTemplate
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(RedisTopicListener.class)
    RedisTopicListener redisTopicListener(
            RedisMessageListenerContainer container,
            StringRedisTemplate stringRedisTemplate) {
        //监听的主题
        List<ChannelTopic> topics = Lists.newArrayList();
        topics.add(new ChannelTopic(CacheConstant.WS_CHAT_TOPIC));
        topics.add(new ChannelTopic(CacheConstant.WS_PUSH_TOPIC));
        // 指定监听的 topic
        RedisTopicListener redisTopicListener = new RedisTopicListener(container,topics);
        redisTopicListener.setStringRedisSerializer(new StringRedisSerializer());
        redisTopicListener.setStringRedisTemplate(stringRedisTemplate);
        return redisTopicListener;
    }
}
